package top.xia17.plugins.fast.common.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import top.xia17.plugins.fast.common.security.base.LoginInfo;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * security的工具类
 * @author xia17
 * @date 2020/7/16 17:04
 */
public class SecUtil {


    /**
     * 获取认证信息
     * @return 认证信息接口
     */
    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取认证信息中的主要用户信息
     * @return /
     */
    public static Object getPrincipal(){
        Authentication authentication = getAuthentication();
        return authentication == null ? null : authentication.getPrincipal();
    }

    /**
     * 获取登录信息
     * @return /
     */
    public static LoginInfo getLoginInfo(){
        Object principal = getPrincipal();
        if (principal == null){
            return null;
        }
        return (LoginInfo) principal;
    }

    /**
     * 获取权限信息
     *
     * @return /
     */
    public static List<String> getAuthorityList() {
        return getAuthentication().getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
    }

    /**
     * 获取Token
     * @return /
     */
    public static String getToken(){
        Authentication authentication = getAuthentication();
        return authentication.getCredentials().toString();
    }

    /**
     * 获取登录的用户ID
     * @return /
     */
    public static Serializable getUserId(){
        LoginInfo loginInfo = getLoginInfo();
        if (loginInfo == null){
            return null;
        }
        return loginInfo.getUserId();
    }

    /**
     * 获取登录的用户名
     * @return /
     */
    public static String getUsername(){
        LoginInfo loginInfo = getLoginInfo();
        if (loginInfo == null){
            return null;
        }
        return loginInfo.getUsername();
    }

}
